﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.PM2.Models.Online;
using Newtonsoft.Json;
using System.Web.Routing;
using DHQGHN.PM2.Models;
using DHQGHN.PM2.ViewModels.Online;
using System.Runtime.Serialization.Json;
using BotDetect.Web.UI.Mvc;
using BotDetect.Web;
using System.Net;

namespace DHQGHN.PM2.Controllers
{
    public class CollectHouseHoldInfoController : BaseController
    {
        private const string DEFAULT_CODE = "-1";
        private const string LEVEL_DEFAULT = "1";
        private const string MESSAGE = "MESSAGE";
        private const string DISTRICT_CODE = "DISTRICT_CODE";
        private const string LIST_HOUSEHOLD = "LIST_HOUSEHOLD";
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(CollectHouseHoldInfoController));

        public ActionResult CollectHouseHoldInfo(string houseHoldID)
        {
            if (houseHoldID != null && houseHoldID.Trim().Length > 0)
            {
                return View();
            }
            else
            {
                return View();
            }
        }

        public ActionResult CollectResidentInfo()
        {
            return View();
        }

        public ActionResult HouseHoldList()
        {
            List<HouseHoldDetailPartialViewModel> listHH = new List<HouseHoldDetailPartialViewModel>();
            try
            {
                using (WebClient wc = new WebClient())
                {
                    if (ModelState.IsValid)
                    {
                        Helper.SetHeaderInfo(wc, "GetAllByUserName");
                        wc.Encoding = Encoding.UTF8;
                        wc.Headers["Content-type"] = "application/json; charset=utf-8";

                        string UrlPath = string.Format("{0}{1}{2}", serviceUrl, "HouseHoldService.svc/GetAllByUserName/", MyUser.UserName);
                        string listhousehold = wc.DownloadString(UrlPath);
                        listHH = JsonConvert.DeserializeObjectAsync<List<HouseHoldDetailPartialViewModel>>(listhousehold).Result;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.StackTrace.ToString());
                throw;
            }
            //ViewData[DISTRICT_CODE] = GetAdministrativeUnit(DEFAULT_CODE, LEVEL_DEFAULT);
            return View(listHH);
        }

        public ActionResult SaveInfo(TemplateDataUploadClient model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (WebClient wc = new WebClient())
                    {
                        Helper.SetHeaderInfo(wc, "AddDataFromClient");
                        wc.Encoding = Encoding.UTF8;
                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                        string UrlPath = string.Format("{0}{1}", serviceUrl, "UploadDataFromClientService.svc/AddDataFromClient");
                        if (model == null)
                        {
                            return Json(String.Empty);
                        }
                        else
                        {
                            if (model.ADDRESS == null)
                            {
                                model.ADDRESS = new List<AddressModel>();
                            }
                            if (model.ADM_UNIT_EXT == null)
                            {
                                model.ADM_UNIT_EXT = new List<AdministrativeUnitExtModels>();
                            }
                            if (model.RESIDENT == null)
                            {
                                model.RESIDENT = new List<Models.Online.ResidentModel>();
                            }
                            string json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(model);
                            string result = wc.UploadString(UrlPath, "POST", json);

                            if (result != null && result.Length > 0)
                            {
                                LogStream.Write<TemplateDataUploadClient>(MyUser.UserName,
                                    CommonData.AppName,
                                    GetFunction(),
                                    "Lưu dữ liệu - SaveInfo", model);
                                return Redirect("CollectResidentInfo");
                            }
                            else
                                return Redirect("CollectHouseHoldInfo");
                        }
                    }
                }
                return Redirect("CollectHouseHoldInfo");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public ActionResult GetInfo(string residentId)
        {
            ThongTinCaNhanModel ttcn = new ThongTinCaNhanModel();
            try
            {
                using (WebClient wc = new WebClient())
                {
                    if (ModelState.IsValid)
                    {
                        Helper.SetHeaderInfo(wc, "GetThongtincanhan");
                        wc.Encoding = Encoding.UTF8;
                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                        string UrlPath = string.Format("{0}{1}", serviceUrl, "OnlineService.svc/GetThongtincanhan");
                        var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(residentId);
                        string result = wc.UploadString(UrlPath, "POST", json);
                        ttcn = JsonConvert.DeserializeObjectAsync<ThongTinCaNhanModel>(result).Result;
                    }

                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            //ViewData[DISTRICT_CODE] = GetAdministrativeUnit(DEFAULT_CODE, LEVEL_DEFAULT);
            return View(ttcn);
        }

        List<SelectListItem> GetAdministrativeUnit(string code, string level)
        {
            try
            {
                List<AdministrativeUnitModel> areaList = new List<AdministrativeUnitModel>();

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetByIdParentTablet");
                    wc.Encoding = Encoding.UTF8;
                    List<SelectListItem> lstItems = new List<SelectListItem>();
                    string UrlPath = string.Format("{0}{1}{2}/{3}", serviceUrl, "AdminUnitService.svc/GetByIdParentTablet/", code, level);
                    string areaDownload = wc.DownloadString(UrlPath);

                    areaList = JsonConvert.DeserializeObjectAsync<List<AdministrativeUnitModel>>(areaDownload).Result;
                    if ("1".Equals(level))
                    {
                        lstItems.Add(new SelectListItem
                        {
                            Value = "-1",
                            Text = "-- Chọn Tỉnh --"
                        });
                    }
                    foreach (var area in areaList)
                    {
                        if (area != null)
                            lstItems.Add(new SelectListItem
                            {
                                Value = area.CODE.ToString(),
                                Text = area.ADM_NAME
                            });
                    }
                    return lstItems;
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public ActionResult GetListHouseHold(string enumeratorID)
        {
            ThongTinCaNhanModel ttcn = new ThongTinCaNhanModel();
            try
            {
                using (WebClient wc = new WebClient())
                {
                    if (ModelState.IsValid)
                    {
                        Helper.SetHeaderInfo(wc, "GetThongtincanhan");
                        wc.Encoding = Encoding.UTF8;
                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                        string UrlPath = string.Format("{0}{1}", serviceUrl, "OnlineService.svc/GetThongtincanhan");
                        var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(enumeratorID);
                        string result = wc.UploadString(UrlPath, "GET", json);
                        ttcn = JsonConvert.DeserializeObjectAsync<ThongTinCaNhanModel>(result).Result;
                    }

                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            //ViewData[DISTRICT_CODE] = GetAdministrativeUnit(DEFAULT_CODE, LEVEL_DEFAULT);
            return View(ttcn);
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public ActionResult GetListHouseHoldOfEnum()
        {
            HouseHoldDetailPartialViewModel listHH = new HouseHoldDetailPartialViewModel();
            try
            {
                using (WebClient wc = new WebClient())
                {
                    if (ModelState.IsValid)
                    {
                        Helper.SetHeaderInfo(wc, "GetAllByUserName");
                        wc.Encoding = Encoding.UTF8;
                        wc.Headers["Content-type"] = "application/json; charset=utf-8";

                        string UrlPath = string.Format("{0}{1}{2}", serviceUrl, "HouseHoldService.svc/GetAllByUserName/", MyUser.UserName);
                        string listhousehold = wc.DownloadString(UrlPath);
                        listHH = JsonConvert.DeserializeObjectAsync<HouseHoldDetailPartialViewModel>(listhousehold).Result;
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            //ViewData[DISTRICT_CODE] = GetAdministrativeUnit(DEFAULT_CODE, LEVEL_DEFAULT);
            return View(listHH);
        }

        [HttpPost]
        [AjaxValidateAntiForgeryToken]
        public ActionResult DeleteListHouseHold(string[] strHouseHoldID)
        {
            try
            {
                using (WebClient wc = new WebClient())
                {
                    if (strHouseHoldID.Length > 0)
                    {
                        if (strHouseHoldID != null)
                        {
                            foreach (string str in strHouseHoldID)
                            {
                                if (str != null && str.Trim().Length > 0)
                                {
                                    Helper.SetHeaderInfo(wc, "DeleteHouseHold");
                                    wc.Encoding = Encoding.UTF8;
                                    wc.Headers["Content-type"] = "application/json; charset=utf-8";
                                    string UrlPath = string.Format("{0}{1}", serviceUrl, "HouseHoldService.svc/DeleteHouseHold");
                                    var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(str);
                                    wc.UploadString(UrlPath, "POST", json);
                                }
                            }
                        }
                    }
                    if (strHouseHoldID.Length > 0)
                    {
                        LogStream.Write(MyUser.UserName,
                                    CommonData.AppName,
                                    GetFunction(),
                                    CommonData.GetListId(strHouseHoldID), "Xóa hộ dân - DeleteListHouseHold");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            //return RedirectToAction("CollectHouseHoldInfo", new { @houseHoldID = "" });
            return CollectHouseHoldInfo(String.Empty);
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public ActionResult UpdateListHouseHold(string strHouseHoldID)
        {
            try
            {
                using (WebClient wc = new WebClient())
                {
                    if (strHouseHoldID != null && strHouseHoldID.Trim().Length > 0)
                    {
                        Helper.SetHeaderInfo(wc, "DeleteHouseHold");
                        wc.Encoding = Encoding.UTF8;
                        wc.Headers["Content-type"] = "application/json; charset=utf-8";
                        string UrlPath = string.Format("{0}{1}", serviceUrl, "HouseHoldService.svc/DeleteHouseHold");
                        var json = new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(strHouseHoldID);
                        wc.UploadString(UrlPath, "POST", json);

                        LogStream.Write(MyUser.UserName,
                                   CommonData.AppName,
                                   GetFunction(),
                                   CommonData.GetListId(new string[] { strHouseHoldID }), "Xóa hộ dân - UpdateListHouseHold");
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return HouseHoldList();
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public JsonResult GetAreaByUsername()
        {
            try
            {
                List<AreaEnumModel> areaList = new List<AreaEnumModel>();

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetByUserName");
                    wc.Encoding = Encoding.UTF8;
                    List<SelectListItem> lstItems = new List<SelectListItem>();
                    string UrlPath = string.Format("{0}{1}/{2}/{3}", serviceUrl, "AreaService.svc", "GetByUserName", MyUser.UserName);
                    string areaDownload = wc.DownloadString(UrlPath);

                    areaList = JsonConvert.DeserializeObjectAsync<List<AreaEnumModel>>(areaDownload).Result;

                    foreach (AreaEnumModel area in areaList)
                    {
                        if (area != null)
                        {
                            lstItems.Add(new SelectListItem
                            {
                                Value = area.AREA_ID,
                                Text = area.AREA_NAME
                            });
                        }
                    }
                    return Json(lstItems, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ;
            }
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public JsonResult GetADMNameByAreaID(string areaID, string type)
        {
            try
            {
                List<AreaEnumModel> areaList = new List<AreaEnumModel>();

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetNameByAreaID");
                    wc.Encoding = Encoding.UTF8;
                    List<SelectListItem> lstItems = new List<SelectListItem>();
                    string UrlPath = string.Format("{0}{1}/{2}/{3}/{4}", serviceUrl, "AdministrativeUnitExtService.svc", "GetNameByAreaID", areaID, type);
                    string areaDownload = wc.DownloadString(UrlPath);

                    areaList = JsonConvert.DeserializeObjectAsync<List<AreaEnumModel>>(areaDownload).Result;

                    foreach (AreaEnumModel area in areaList)
                    {
                        if (area != null)
                            lstItems.Add(new SelectListItem
                            {
                                Value = area.AREA_ID,
                                Text = area.AREA_NAME
                            });
                    }
                    return Json(lstItems, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        [HttpGet]
        [AjaxValidateAntiForgeryToken]
        public JsonResult GetNameByAdmUnitExtID(string admUnitExtID, string level)
        {
            try
            {
                List<AreaEnumModel> areaList = new List<AreaEnumModel>();

                using (WebClient wc = new WebClient())
                {
                    Helper.SetHeaderInfo(wc, "GetNameByAdmUnitExtID");
                    wc.Encoding = Encoding.UTF8;
                    List<SelectListItem> lstItems = new List<SelectListItem>();
                    string UrlPath = string.Format("{0}{1}/{2}/{3}/{4}", serviceUrl, "AdministrativeUnitExtService.svc", "GetNameByAdmUnitExtID", admUnitExtID, level);
                    string areaDownload = wc.DownloadString(UrlPath);

                    areaList = JsonConvert.DeserializeObjectAsync<List<AreaEnumModel>>(areaDownload).Result;

                    foreach (AreaEnumModel area in areaList)
                    {
                        if (area != null)
                            lstItems.Add(new SelectListItem
                            {
                                Value = area.AREA_ID,
                                Text = area.AREA_NAME
                            });
                    }
                    return Json(lstItems, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw ex;
            }
        }

        private string GetFunction()
        {
            return "Quản lý thông tin hộ dân cư - CollectHouseHoldInfoController";
        }
    }
}